//
//  MCPlanVc.swift
//  MCBodyBuildingPro
//
//  Created by Renlvshijie on 2023/5/4.
//

import UIKit
import SnapKit
import QMUIKit
import Toast_Swift
import MJRefresh
import ObjectMapper
import Kingfisher
import RxCocoa
import RxSwift
import EachNavigationBar

class MCPlanVc: MCBaseVc {
    
    let MCPlanTableViewIdentifier = "MCPlanTableViewIdentifier"
    let MCPlanProgressTableViewIdentifier = "MCPlanProgressTableViewIdentifier"
    let MCChatGPTTableViewIdentifier = "MCChatGPTTableViewIdentifier"
    let MCSpecialTrainingTableViewIdentifier = "MCSpecialTrainingTableViewIdentifier"
    
    var planTableView:UITableView!
    
    var current:Int = 1
    
    private var dataSource:Array = [HomeRecommandRecord?]()
    private var todayPlanDataSource:Array = [HomeTodayListModel?]()
    
    let dispose:DisposeBag = DisposeBag()
    
   
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let headerNavigationView = UIView.init()
        let navigationImage = UIImageView.init(image: UIImage(named: "home_master_image"))
//        navigationImage.frame = CGRect(x: 0, y: 15, width: 80, height: 20)
        headerNavigationView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40)
        headerNavigationView.addSubview(navigationImage)
        navigationImage.snp.makeConstraints { make in
            make.trailing.equalTo(8)
            make.centerY.equalTo(headerNavigationView.snp.centerY)
        }
//        let navititleLabel = QMUILabel.init()
//        navititleLabel.text = "·运动健身与健康"
//        navititleLabel.font = UIFont(name: "PingFangSC-Regular", size: 12)
//        navititleLabel.textColor = UIColor.qmui_color(withHexString: "#10151C")
//        headerNavigationView.addSubview(navititleLabel)
//        navititleLabel.snp.makeConstraints { make in
//            make.left.equalTo(navigationImage.snp.right).offset(0.0)
//            make.centerY.equalTo(navigationImage.snp.centerY).offset(0.0)
//        }
        self.navigationItem.titleView = headerNavigationView
        
        
        let rightBtn = QMUIButton.init()
        rightBtn.setBackgroundImage(UIImage(named: "home_right_navigation_image"), for: .normal)
        rightBtn.addTarget(self, action: #selector(rightAction), for: .touchUpInside)
        rightBtn.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
        rightBtn.rx.tap.subscribe(onNext: { event in
           //
            let datePlayVc = MCDatePlayVc.init()
            datePlayVc.hidesBottomBarWhenPushed = true

            self.navigationController?.pushViewController(datePlayVc, animated: true)
        }).disposed(by: dispose)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBtn)
        
        
        self.view.backgroundColor = UIColor.qmui_color(withHexString: "#F7F7F9")
        planTableView = UITableView.init(frame:CGRect.zero, style: .grouped)
        planTableView.backgroundColor = UIColor.qmui_color(withHexString: "#F7F7F9")
        planTableView.delegate = self
        planTableView.dataSource = self
        planTableView.separatorStyle = .none
        planTableView.showsVerticalScrollIndicator = false
        view.addSubview(planTableView!)
        planTableView.snp.makeConstraints { make in
            make.left.equalTo(view.snp.left).offset(16)
            make.right.equalTo(view.snp.right).offset(-16)
            make.bottom.equalTo(view.snp.bottom).offset(0)
            make.top.equalTo(view.snp.top).offset(0)
        }
        
        self.planTableView.register(UINib.init(nibName: "MCChatGPTCell", bundle: Bundle.main), forCellReuseIdentifier: MCChatGPTTableViewIdentifier)
        self.planTableView.register(UINib.init(nibName: "MCProgressTableCell", bundle: Bundle.main), forCellReuseIdentifier: MCPlanProgressTableViewIdentifier)
        self.planTableView.register(UINib.init(nibName: "MCPlanTableCell", bundle: Bundle.main), forCellReuseIdentifier: MCPlanTableViewIdentifier)
        self.planTableView.register(UINib(nibName: "MCSpecialTrainTableCell", bundle: Bundle.main), forCellReuseIdentifier: MCSpecialTrainingTableViewIdentifier)
        
        
        self.planTableView.tableFooterView = UIView.init()
        self.planTableView.sectionFooterHeight = 10.0
        
        
        self.todayInfo()
        
        self.planTableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.current = 1
            self.recommand(current: self.current)
        })
        
        self.planTableView.mj_header?.beginRefreshing()
        
        self.planTableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {
            self.recommand(current: self.current)
        })
       
        
    }
    
    @objc func rightAction() -> Void {
        
    }
        
    //专项训练
    func specializedTraining() -> Void {
        recommand(current: 1)
    }
    
    //推荐计划
    func recommand(current:Int?) -> Void {
        NetWorkRequest(HomePlanApi.recommandPlan(current: current, planType: 0)) { ResponseModel in
            let recommandList = HomeRecommandInfoListModel.init(JSONString: ResponseModel.dataString)
            self.planTableView.mj_header?.endRefreshing()
            self.planTableView.mj_footer?.endRefreshing()
            if current == 1 {
                self.dataSource.removeAll()
                self.dataSource.append(contentsOf:  recommandList?.records ?? [])
            }else {
                self.current += 1
                self.dataSource.append(contentsOf:  recommandList?.records ?? [])
            }
            self.planTableView.reloadData()
        } failureCallback: { ResponseModel in
            self.planTableView.mj_header?.endRefreshing()
            self.planTableView.mj_footer?.endRefreshing()
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    
    //今天计划
    func todayInfo() -> Void {
        NetWorkRequest(HomePlanApi.todayPlan(today:SXDateTool.getCurrentTime(timeFormat:.YYYYMMDD))) { ResponseModel in
            if ResponseModel.code == 200 {
                self.todayPlanDataSource.append(contentsOf: Mapper<HomeTodayListModel>().mapArray(JSONString: ResponseModel.dataString) ?? [])
                self.planTableView.reloadData()
            }else {
                self.view.makeToast("网络失败",position: .center)
            }
        } failureCallback: { ResponseModel in
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    
    @objc func pushCreate() -> Void {
        let myPlanVc = MCMyPlanVc.init()
        myPlanVc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(myPlanVc, animated: true)
    }
    
    
}

extension MCPlanVc:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 70
        }else if indexPath.section == 1 {
            return 70
        }else if indexPath.section == 2 {
            return 250
        }else {
            return 70
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }else if section == 1 {
            return self.todayPlanDataSource.count
        }else if section == 2{
            return 1
        } else {
            return self.dataSource.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell:MCChatGPTCell = tableView.dequeueReusableCell(withIdentifier: MCChatGPTTableViewIdentifier, for: indexPath) as! MCChatGPTCell
            
            return cell
        }else if indexPath.section == 1{
            let cell:MCProgressTableCell = tableView.dequeueReusableCell(withIdentifier: MCPlanProgressTableViewIdentifier, for: indexPath) as! MCProgressTableCell
            let model = todayPlanDataSource[indexPath.row]
            cell.configCell(model: model)
            return cell
        }else if indexPath.section == 2 {
            let cell:MCSpecialTrainTableCell = tableView.dequeueReusableCell(withIdentifier: MCSpecialTrainingTableViewIdentifier, for: indexPath) as! MCSpecialTrainTableCell
            
            return cell
        } else{
            let cell:MCPlanTableCell = tableView.dequeueReusableCell(withIdentifier: MCPlanTableViewIdentifier, for: indexPath) as! MCPlanTableCell
            let recoreds = self.dataSource[indexPath.row]
            
            cell.HeaderIconImageView.kf.setImage(with:URL(string: recoreds?.planUrl ?? ""))
            cell.titleInfoLabel.text = recoreds?.planName ?? ""
            
            
           for subView  in cell.LabelLayoutView.subviews {
               subView.removeFromSuperview()
            }
            
            
            let paddingLabel = QMUIButton.init()
            paddingLabel.backgroundColor = UIColor.qmui_color(withHexString:"#35DE94")?.withAlphaComponent(0.1)
            paddingLabel.setTitleColor( UIColor.qmui_color(withHexString: "#35DE94"), for: .normal)
            
            paddingLabel.setTitle("L\(String(describing:(recoreds?.planLevel ?? 0)))", for: .normal)
            paddingLabel.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
            paddingLabel.layer.cornerRadius = 5
            paddingLabel.titleLabel?.font = UIFont(name: "PingFangSC-Regular", size: 10)
            paddingLabel.layer.masksToBounds = true
            cell.LabelLayoutView.addSubview(paddingLabel)
            
            return cell
        }
        
    }
    
    ///
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0.01
        }else if section == 1 {
            return 45
        }else if section == 2 {
            return 45
        }else if section == 3 {
            return 45
        } else{
            return 0.01
        }
        
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let headerView = MCSectionHeaderView().initHeaderView()
       
        if section == 0 {
            headerView.titleLab.isHidden = true
            headerView.timeLabel.isHidden = true
            headerView.enterImageView.isHidden = true
        }else if section == 1 {
            headerView.titleLab.isHidden = false
            headerView.timeLabel.isHidden = false
            headerView.enterImageView.isHidden = false
            headerView.timeLabel.text = "\(SXDateTool.getCurrentTime(timeFormat:.YYYYMMDD)) \(SXDateTool.getNowWeekday())"
            headerView.isUserInteractionEnabled = true
            let headerCreatPlan = UITapGestureRecognizer(target: self, action: #selector(pushCreate))
            headerView.addGestureRecognizer(headerCreatPlan)
        }else if section == 2 {
            headerView.isUserInteractionEnabled = false
            headerView.titleLab.isHidden = false
            headerView.titleLab.text = "专项训练"
            headerView.timeLabel.isHidden = true
            headerView.enterImageView.isHidden = true
        }else if section == 3 {
            headerView.isUserInteractionEnabled = false
            headerView.titleLab.isHidden = false
            headerView.titleLab.text = "推荐计划"
            headerView.timeLabel.isHidden = true
            headerView.enterImageView.isHidden = true
        }
        
        return headerView

    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            let chatGPTIMVc = MCChatGPTIMVc.init()
            chatGPTIMVc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(chatGPTIMVc, animated: true)
        }else if indexPath.section == 1 {
            let videoTranNofitVc = MCVIdeoTranNofitVc.init()
            videoTranNofitVc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(videoTranNofitVc, animated: true)
        }else if indexPath.section == 2 {
            
        }else if indexPath.section == 3 {
            
            let recoreds = self.dataSource[indexPath.row]
            let traindetailPlanVc = MCTraindetailPlanVc.init()
            traindetailPlanVc.ids = recoreds?.id
            traindetailPlanVc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(traindetailPlanVc, animated: true)
        }
    }
    
}

